<?php

namespace App\Imports;

use App\Services\Designer\Model\Performance;
use App\Services\Designer\Model\Designer;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Auth;
use Validator;


/**
 * 设计师绩效数据Excel导入
 *
 * php-docblocker.extra
 */
class PerformanceImport implements ToCollection,WithHeadingRow{

    private $userId;

    // 设计师ID 校验
    private $erpUserIdsStr = '';

    // 订单等级 校验
    private $orderLevelsStr = '一星单,三星单,五星单';

    // 费用类型 校验
    private $costCategorysStr = '免费,收费';

    // 收费等级 校验
    private $chargeLevelsStr = '免费,中级,高级,资深,整装';


    // 存储通过校验的数据
    private $validatedData = [];

    public function __construct()
    {
        // Designer id 数组，转为字符串，用于校验 erp_user_id 列
        $this->erpUserIdsStr = implode(',',Designer::pluck('id')->toArray());
    }

   /**
    * 导入到集合
    *
    * @param Collection $rows
    * @return void
    * php-docblocker.extra
    */
    public function collection(Collection $rows)
    {
        // 字段的校验规则
        $rules = [
            'shop_name' => 'required',
            'erp_user_id' => "required|in:$this->erpUserIdsStr",
            'order_level' => "required|in:$this->orderLevelsStr",
            'cost_category' => "required|in:$this->costCategorysStr",
            'charge_level' => "required|in:$this->chargeLevelsStr",
            'time' => "required|date",
        ];

        foreach ($rows as $row) {
            $validator = Validator::make($row->toArray(), $rules);

            if ($validator->fails()) {
                $this->validatedData = false;
                return;
            }

            $this->validatedData[] = $row->toArray();
        }
    }

    public function getValidatedData()
    {
        return $this->validatedData;
    }


    /**
     * Undocumented function
     * 标题在第二行
     * @return integer
     * php-docblocker.extra
     */
    public function headingRow(): int
    {
        return 2;
    }
}



